package com.lottery.service.pc28.lobbyService.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.dao.pc28.accoutDao.UserDao;
import com.lottery.dto.Message;
import com.lottery.dto.MessageTube;
import com.lottery.entity.User;
import com.lottery.service.pc28.lobbyService.BarrageService;
import com.lottery.utils.MessageTubes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class BarrageServiceImpl implements BarrageService {

	@Autowired
	private UserDao userDao;

	private MessageTubes messageTubes = MessageTubes.getInstance();

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 插入弹幕
	 * 
	 * @param userId
	 *            用户id
	 * @param barrage
	 *            要写入管道的弹幕
	 * @return
	 */
	public String insertBarrage(int userId, String barrage, int lotteyType) {
		JSONObject jObject = new JSONObject();
		User selectId = null;
		try {
			selectId = userDao.selectId(userId);
		} catch (Exception e) {
			jObject.put("result", "1");
			jObject.put("msg", "错误");
			return jObject.toJSONString();
		}
		String body = userId + "::" + selectId.getUserName() + "::" + selectId.getHeadPic() + "::" + barrage;
		Message message = new Message();
		message.setMessageBody(body);
		message.setTimestamp(new Date().getTime());

		MessageTube messageTube;
		if (lotteyType == 1) {
			messageTube = messageTubes.getSscBarMessageTube();
		} else {
			messageTube = messageTubes.getPc28BarMessageTube();
		}
		int index = messageTube.push(message);
		logger.debug("put message2 index：{}", index);
		jObject.put("result", "0");
		return jObject.toJSONString();
	}

	/**
	 * 获得弹幕
	 * 
	 * @param index
	 *            上一次最后一条数据的index
	 * @return
	 */
	public String queryBarrage(int index, int lotteyType) {
		Map<String, Object> maxmap = new HashMap<String, Object>();
		List<Message> checkMessage2 = new ArrayList<>();
		try {
			// 获得上次到现在的所有弹幕
			List<Message> checkMessage;
			if (lotteyType == 1) {
				checkMessage = messageTubes.getSscBarMessageTube().checkMessage(index + 1);
			} else {
				checkMessage = messageTubes.getPc28BarMessageTube().checkMessage(index + 1);
			}
			long time = new Date().getTime();
			// 截取2分钟 以内的信息
			for (int i = 0; i < checkMessage.size(); i++) {
				if (time - checkMessage.get(i).getTimestamp() <= 120000) {
					List<Message> subList = checkMessage.subList(i, checkMessage.size());

					ArrayList<Map<String, String>> listMap = new ArrayList<>();
					int reIndex = 0;
					for (Message message : subList) {
						Map<String, String> map = new HashMap<String, String>();
						String messageBody = message.getMessageBody();
						String[] split = messageBody.split("::");
						map.put("userId", split[0]);
						map.put("userName", split[1]);
						map.put("headPic", split[2]);
						map.put("barrage", split[3]);
						listMap.add(map);
						reIndex = message.getIndex();
					}

					maxmap.put("array", listMap);
					maxmap.put("msg", "成功");
					maxmap.put("message", reIndex + "");
					maxmap.put("result", "0");
					return JSON.toJSONString(maxmap, true);
				}
			}
			maxmap.put("array", checkMessage2);
			maxmap.put("result", "0");
			maxmap.put("message", index + "");
			maxmap.put("msg", "成功");
			logger.debug("checkMessage2::,{}", checkMessage2);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryBarrage error:", e);
			maxmap.put("result", "100");
			maxmap.put("msg", "失败");
		}
		return JSON.toJSONString(maxmap, true);
	}

}
